package com.fxcalibre.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.fxcalibre.syncservices.imdb.LookupVO;

public class HTTPUtils
{
	public static boolean testConnection(String address)
	{
		URL url = null;
		try
		{
			url = new URL(address);
		} catch (MalformedURLException e)
		{
			return false;
		}
		HttpURLConnection connection = null;
		try
		{
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("User-Agent", "Mozilla/7.0");
		} catch (IOException e)
		{
			return false;
		}
		try
		{
			connection.connect();
			if (connection.getResponseCode() != 200)
				return false;
		} catch (IOException localIOException1)
		{
			return false;
		}
		return true;
	}

	public static LookupVO sendRequest(LookupVO lookupVO)
	{
		StringBuffer messageBuffer = new StringBuffer();
		try
		{
			String urlString = lookupVO.getUrl();
			urlString = urlString.replaceAll(" ", "%20");

			URL server = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) server.openConnection();
			connection.setRequestProperty("User-Agent", "Mozilla/7.0");
			connection.connect();

			if (connection.getResponseCode() != 200)
			{
				System.out.println("connection.getResponseCode(): " + connection.getResponseCode());
				return null;
			}

			lookupVO.setUrl("http://" + connection.getURL().getHost() + connection.getURL().getPath());

			InputStream is = connection.getInputStream();
			DataInputStream dis = new DataInputStream(is);
			int ch;
			while ((ch = is.read()) != -1)
			{
				messageBuffer.append((char) ch);
			}
			dis.close();
			is.close();
			connection.disconnect();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		lookupVO.setResult(messageBuffer.toString());
		messageBuffer = null;
		return lookupVO;
	}

	public static void downloadImage(String urlImage, String fileName) throws IOException
	{
		// lets say saving the png file from google.
		URL url = new URL(urlImage);
		URLConnection urlConnection = url.openConnection();

		// creating the input stream from google image
		BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
		// my local file writer, output stream
		String imgDirStr = (String) Preferences.getPreferences().get(Constants.KEY_DB_FILE) + "/db/imgs/";
		File imgDir = new File(imgDirStr);
		System.out.println("imgDir: " + imgDir.getAbsolutePath());
		if (!imgDir.exists())
		{
			System.out.println("Creando directorio");
			imgDir.mkdir();
		}

		File imgFile = new File(imgDirStr + fileName);
		if (!imgFile.exists())
		{
			System.out.println("Imagen: " + imgFile.getAbsolutePath());
			System.out.println(imgFile.canWrite());
			imgFile.createNewFile();
		}

		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imgFile));

		// until the end of data, keep saving into file.
		int i;
		while ((i = in.read()) != -1)
		{
			out.write(i);
		}
		out.flush();

		// closing all the shits
		out.close();
		in.close();
	}

	public static void main(String[] args) throws IOException
	{
		System.out.println("");
		HTTPUtils.downloadImage("http://ia.media-imdb.com/images/M/MV5BMjA1MjE2MTQ2MV5BMl5BanBnXkFtZTcwMjE5MDY0Nw@@._V1._SX214_CR0,0,214,314_.jpg", "1.jpg");
	}
}